<template>
  <view class="patient-detail">
    <view class="page-header">
      <view class="back-btn" @click="goBack">
        <uni-icons type="back" size="20" color="#333"></uni-icons>
      </view>
      <text class="header-title">患者详情</text>
      <view class="header-right">
        <button class="diagnose-btn" @click="startDiagnosis">开始诊断</button>
      </view>
    </view>
    
    <scroll-view scroll-y class="scroll-container">
      <!-- 基本信息卡片 -->
      <view class="info-card">
        <view class="profile-header">
          <uni-icons type="person" size="60" color="#2979ff"></uni-icons>
          <view class="profile-info">
            <view class="name-line">
              <text class="name">{{ patient?.name || '加载中...' }}</text>
              <text class="gender-tag">{{ patient?.sex === 'male' ? '男' : '女' }}</text>
            </view>
            <view class="basic-info">
              <text>{{ patient?.age || '--' }}岁</text>
              <text class="blood-type">{{ patient?.bloodType || '未知' }}型血</text>
            </view>
            <view class="phone-info">
              <uni-icons type="phone" size="14" color="#666"></uni-icons>
              <text class="phone">{{ patient?.phone || '--' }}</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 健康状态卡片 -->
      <view class="health-card">
        <view class="card-header">
          <text class="card-title">实时健康数据</text>
          <text class="update-time">{{ formatDateTimeDisplay(healthData?.collectTime) }}</text>
        </view>
        <view class="health-grid">
          <view class="health-item">
            <uni-icons type="heart" size="30" color="#2979ff"></uni-icons>
            <text class="value">{{ healthData?.heartRate || '--' }}</text>
            <text class="label">心率 (次/分)</text>
          </view>
          <view class="health-item">
            <uni-icons type="pulse" size="30" color="#2979ff"></uni-icons>
            <text class="value">{{ healthData?.bloodPressureHigh || '--' }}/{{ healthData?.bloodPressureLow || '--' }}</text>
            <text class="label">血压 (mmHg)</text>
          </view>
          <view class="health-item">
            <uni-icons type="circle" size="30" color="#2979ff"></uni-icons>
            <text class="value">{{ healthData?.bloodOxygen || '--' }}%</text>
            <text class="label">血氧</text>
          </view>
          <view class="health-item">
            <uni-icons type="thermometer" size="30" color="#2979ff"></uni-icons>
            <text class="value">{{ healthData?.bodyTemperature || '--' }}°C</text>
            <text class="label">体温</text>
          </view>
        </view>
      </view>
      
      <!-- 过敏药物卡片 -->
      <view class="section-card">
        <view class="section-header">
          <text class="section-title">过敏药物</text>
        </view>
        <view class="allergy-content">
          <view v-if="allergyList && allergyList.length" class="allergy-list">
            <uni-tag 
              v-for="allergy in allergyList" 
              :key="allergy.id"
              :text="allergy.medicationName"
              type="error"
              class="allergy-tag"
            />
          </view>
          <view v-else class="empty-tip">
            <uni-icons type="info" size="40" color="#999"></uni-icons>
            <text>暂无过敏药物记录</text>
          </view>
        </view>
      </view>
      
      <!-- 用药记录卡片 -->
      <view class="section-card">
        <view class="section-header">
          <text class="section-title">用药记录</text>
          <uni-icons type="right" size="20" color="#ccc"></uni-icons>
        </view>
        <view class="medication-list">
          <view 
            v-if="hasMedicalRecord"
            v-for="med in medicationList.slice(0, 3)" 
            :key="med.id" 
            class="med-item"
          >
            <view class="med-name">{{ med.medicationName }}</view>
            <view class="med-details">
              <text>{{ med.dosage }}</text>
              <text class="dot-divider">•</text>
              <text>{{ med.frequency }}</text>
            </view>
            <view class="med-date">{{ med.startDate }} 至 {{ med.endDate }}</view>
          </view>
          <view v-else class="empty-tip">
            <uni-icons type="info" size="40" color="#999"></uni-icons>
            <text>暂无用药记录</text>
          </view>
        </view>
      </view>
      
      <!-- 病历记录卡片 -->
      <view class="section-card">
        <view class="section-header">
          <text class="section-title">病历记录</text>
          <uni-icons type="right" size="20" color="#ccc"></uni-icons>
        </view>
        <view class="record-list">
          <view 
            v-if="hasMedicalRecord" 
            v-for="record in medicalRecordList.slice(0, 3)" 
            :key="record.id" 
            class="record-item"
          >
            <view class="record-hospital">
              <text>{{ record.hospital }}</text>
              <text class="department">{{ record.department }}</text>
            </view>
            <view class="record-diagnosis">诊断: {{ record.diagnosis }}</view>
            <view class="record-date">{{ formatDate(record.time) }}</view>
          </view>
          <view v-else class="empty-tip">
            <uni-icons type="info" size="40" color="#999"></uni-icons>
            <text>暂无病历记录</text>
          </view>
        </view>
      </view>
      
      <!-- 健康数据图表卡片 -->
      <view class="chart-card">
        <view class="chart-header">
          <text class="chart-title">健康趋势</text>
          <view class="chart-tabs">
            <view 
              v-for="tab in tabs" 
              :key="tab.value" 
              class="chart-tab" 
              :class="{ active: activeTab === tab.value }"
              @click="activeTab = tab.value"
            >
              {{ tab.name }}
            </view>
          </view>
        </view>
        <view class="chart-body">
          <view class="chart-placeholder">
            <text>{{ activeTab }}趋势图表</text>
            <text class="chart-note">（图表组件待实现）</text>
          </view>
        </view>
      </view>
    </scroll-view>
    
    <uni-load-more v-if="loading" status="loading"></uni-load-more>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { usePatientStore } from '@/store/modules/useDoctorStore';
import { useRecordStore } from '@/store/modules/useRecordStore';
import { useHealthData } from '@/store/modules/useHealthData';

// 定义组件
const patientStore = usePatientStore();
const recordStore = useRecordStore();
const healthDataStore = useHealthData();

const loading = ref(true);
const patientId = ref(null);
const activeTab = ref('heartRate');

// 图表选项卡
const tabs = [
  { name: '心率', value: 'heartRate' },
  { name: '血压', value: 'bloodPressure' },
  { name: '血氧', value: 'bloodOxygen' },
  { name: '睡眠', value: 'sleep' }
];

// 获取患者信息
const patient = computed(() => patientStore.getCurPatient);

// 获取健康数据
const healthData = computed(() => healthDataStore.getRealtimeHealthData);

// 获取用药列表
const medicationList = computed(() => recordStore.getMedicationList);

// 获取病历记录
const medicalRecordList = computed(() => recordStore.getMedicalRecordList);

// 获取过敏药物
const allergyList = computed(() => recordStore.getAllergyList);

const hasMedicalRecord = computed(() => {
  return medicalRecordList.value && medicalRecordList.value.length > 0;
});

// 页面加载时获取参数
const initData = async (id) => {
  if (!id) {
    console.error('未获取到患者ID参数');
    uni.showToast({
      title: '参数错误',
      icon: 'none'
    });
    return;
  }

  loading.value = true;
  try {
    patientId.value = id;
    console.log('准备加载患者详情，ID:', id);
    
    // 设置当前患者ID
    await patientStore.setCurPatientId(id);
    
    // 设置记录store的当前用户ID
    recordStore.setCurUserId(id);
    
    // 并行获取所有需要的数据
    await Promise.all([
      recordStore.fetchMedicationList(id),
      recordStore.fetchMedicalRecordList(id),
      recordStore.fetchAllergyList(id),
      healthDataStore.fetchRealtimeData(id)
    ]);
    
    console.log('患者详情数据加载成功:', {
      patient: patient.value,
      healthData: healthData.value,
      medicationList: medicationList.value,
      medicalRecordList: medicalRecordList.value,
      allergyList: allergyList.value
    });
  } catch (error) {
    console.error('加载患者详情数据失败:', error);
    uni.showToast({
      title: '加载数据失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 在页面加载时获取参数
onMounted(() => {
  // 获取当前页面实例
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  
  // 尝试多种方式获取参数
  let id = null;
  
  // 方式1：从options中获取
  if (currentPage?.options?.id) {
    id = currentPage.options.id;
  }
  
  // 方式2：从$page中获取
  if (!id && currentPage?.$page?.options?.id) {
    id = currentPage.$page.options.id;
  }
  
  // 方式3：从路由参数中获取
  if (!id && currentPage?.$page?.fullPath) {
    const query = currentPage.$page.fullPath.split('?')[1];
    if (query) {
      const params = new URLSearchParams(query);
      id = params.get('id');
    }
  }
  
  // 方式4：从onLoad参数中获取
  if (!id && currentPage?.$vm?.$scope?.options?.id) {
    id = currentPage.$vm.$scope.options.id;
  }
  
  console.log('页面参数获取结果:', {
    currentPage,
    id,
    options: currentPage?.options,
    $page: currentPage?.$page,
    $vm: currentPage?.$vm
  });
  
  if (id) {
    console.log('准备加载患者详情，ID:', id);
    initData(id);
  } else {
    console.error('未获取到患者ID参数');
    uni.showToast({
      title: '参数错误',
      icon: 'none'
    });
  }
});

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 开始诊断
const startDiagnosis = () => {
  if (!patientId.value) {
    uni.showToast({
      title: '患者信息未加载',
      icon: 'none'
    });
    return;
  }
  
  console.log('准备跳转到诊断页面，患者ID:', patientId.value);
  
  // 先设置当前患者ID
  patientStore.setCurPatientId(patientId.value).then(() => {
    // 确保ID设置成功后再跳转
    uni.navigateTo({
      url: `/pages/role/doctor/diagnose?id=${patientId.value}`,
      success: () => {
        console.log('跳转到诊断页面成功，患者ID:', patientId.value);
      },
      fail: (err) => {
        console.error('跳转到诊断页面失败:', err);
        uni.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  }).catch(err => {
    console.error('设置患者ID失败:', err);
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    });
  });
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '--';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
};

// 格式化日期时间
const formatDateTimeDisplay = (dateString) => {
  if (!dateString) return '暂无数据';
  const date = new Date(dateString);
  return `更新于 ${formatDate(dateString)} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};
</script>

<style lang="scss" scoped>
.patient-detail {
  min-height: 100vh;
  background-color: #f5f7fa;
  position: relative;
}

.page-header {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #ffffff;
  position: sticky;
  top: 0;
  z-index: 10;
  
  .back-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .header-title {
    flex: 1;
    text-align: center;
    font-size: 34rpx;
    font-weight: bold;
  }
  
  .header-right {
    width: 150rpx;
    display: flex;
    justify-content: flex-end;
    
    .diagnose-btn {
      background-color: #2979ff;
      color: #ffffff;
      font-size: 24rpx;
      padding: 10rpx 20rpx;
      border-radius: 30rpx;
      border: none;
    }
  }
}

.scroll-container {
  height: calc(100vh - 80rpx);
  padding-bottom: 30rpx;
}

.info-card, .health-card, .section-card, .chart-card {
  margin: 30rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.profile-header {
  display: flex;
  align-items: center;
  
  .profile-info {
    margin-left: 30rpx;
    
    .name-line {
      display: flex;
      align-items: center;
      margin-bottom: 10rpx;
      
      .name {
        font-size: 34rpx;
        font-weight: bold;
        margin-right: 15rpx;
      }
      
      .gender-tag {
        font-size: 24rpx;
        color: #666;
        background-color: #f2f2f2;
        padding: 2rpx 10rpx;
        border-radius: 6rpx;
      }
    }
    
    .basic-info {
      font-size: 28rpx;
      color: #666;
      margin-bottom: 10rpx;
      
      .blood-type {
        margin-left: 20rpx;
      }
    }
    
    .phone-info {
      display: flex;
      align-items: center;
      font-size: 28rpx;
      color: #666;
      
      .phone {
        margin-left: 10rpx;
      }
    }
  }
}

.card-header, .section-header, .chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  
  .card-title, .section-title, .chart-title {
    font-size: 32rpx;
    font-weight: bold;
  }
  
  .update-time {
    font-size: 24rpx;
    color: #999;
  }
}

.health-grid {
  display: flex;
  flex-wrap: wrap;
  
  .health-item {
    width: 50%;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20rpx 0;
    
    .value {
      font-size: 40rpx;
      font-weight: bold;
      color: #2979ff;
      margin: 15rpx 0 5rpx;
    }
    
    .label {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.allergy-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
  
  .allergy-tag {
    margin-bottom: 10rpx;
  }
}

.med-item, .record-item {
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
    padding-bottom: 0;
  }
  
  .med-name, .record-hospital {
    font-weight: bold;
    font-size: 30rpx;
    margin-bottom: 10rpx;
    
    .department {
      margin-left: 15rpx;
      font-size: 26rpx;
      font-weight: normal;
      color: #666;
    }
  }
  
  .med-details, .record-diagnosis {
    font-size: 28rpx;
    color: #555;
    margin-bottom: 10rpx;
    
    .dot-divider {
      margin: 0 10rpx;
    }
  }
  
  .med-date, .record-date {
    font-size: 24rpx;
    color: #999;
  }
}

.chart-tabs {
  display: flex;
  margin-top: 20rpx;
  overflow-x: auto;
  white-space: nowrap;
  background-color: #f5f7fa;
  border-radius: 100rpx;
  
  .chart-tab {
    padding: 10rpx 30rpx;
    font-size: 26rpx;
    color: #666;
    
    &.active {
      background-color: #2979ff;
      color: #ffffff;
      border-radius: 100rpx;
    }
  }
}

.chart-body {
  min-height: 300rpx;
  margin-top: 20rpx;
  
  .chart-placeholder {
    height: 300rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #999;
    border: 1rpx dashed #ddd;
    border-radius: 10rpx;
    
    .chart-note {
      margin-top: 10rpx;
      font-size: 24rpx;
    }
  }
}

.empty-tip {
  padding: 30rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #999;
  
  text {
    margin-top: 10rpx;
    font-size: 28rpx;
  }
}
</style>